package cn.doctor.assistant.pad.db;

import android.content.Context;
import android.content.SharedPreferences;

import cn.doctor.assistant.pad.MyApplication;

/**
 * Created by admin on 2016/2/22.
 */
public class AssistantPerferences {

    public static final String fileName = "doctor_assistant_pad";

    public static final String KEY_LOGIN_PHONE = "login_phone";
    public static final String KEY_LOGIN_PASSWORD = "login_password";

    public static <T> T get(String key, Class<?> clazz) {
        Context context = MyApplication.getInstance();
        SharedPreferences sp = context.getSharedPreferences(fileName, 0);
        //FIXME 注意，不同的key可能有不同的默认值，修正前需谨慎使用
        if (clazz == Integer.class) {
            return (T) ((Integer) (sp.getInt(key, -1)));
        } else if (clazz == Boolean.class) {
            return (T) ((Boolean) sp.getBoolean(key, false));
        } else if (clazz == String.class) {
            return (T) (sp.getString(key, null));
        } else if (clazz == Long.class) {
            return (T) ((Long) sp.getLong(key, -1L));
        } else if (clazz == Float.class) {
            return (T) ((Float) sp.getFloat(key, -1F));
        } else {
            throw new UnsupportedOperationException("不支持此类型:" + clazz);
        }
    }

    public static void save(String key, Object value) {
        Context context = MyApplication.getInstance();
        SharedPreferences.Editor editor = context.getSharedPreferences(fileName, 0).edit();

        if (value instanceof Integer) {
            editor.putInt(key, (int) value);
        } else if (value instanceof Boolean) {
            editor.putBoolean(key, (boolean) value);
        } else if (value instanceof String) {
            editor.putString(key, (String) value);
        } else if (value instanceof Long) {
            editor.putLong(key, (long) value);
        } else if (value instanceof Float) {
            editor.putFloat(key, (float) value);
        } else {
            throw new UnsupportedOperationException("不支持此类型:" + value);
        }

        editor.commit();
    }

}
